package com.example.permission.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class myConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    /* 配置security用户验证的业务层*/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        //密码加密方式
//        BCryptPasswordEncoder bcpe = new BCryptPasswordEncoder();
//        String password = bcpe.encode("123");//这个就是加密
//        //权限都给他inMemoryAuthentication
//        auth.inMemoryAuthentication().withUser("zhangsan").password(password).roles("admin");
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

    //向spring容器中注入bean对象，告知security密码
    @Bean
    public PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 自定义登陆页面，页面拦截
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/toLoginPage") // 去往登陆页面
                .loginProcessingUrl("/login") // 登陆表单的提交路径
                .defaultSuccessUrl("/index").permitAll() //默认登陆成功后，跳转的页面
                .and().authorizeRequests() //所有请求都要验证,拦截一切
                .antMatchers("/login","/asserts/**").permitAll() //放行登录请求，permitAll全部拦截
                .anyRequest().authenticated() //只要你登陆过了以后，我就让你访问一切。登陆验证成功后，放行所有资源
                .and().csrf().disable(); //跨站请求伪造，关闭csrf防护
    }
}
